Por tal motivo, en cada sección encontrarás algunas transformaciones que nos ayudarán a tener los datos en el formato que necesitas para poder graficar adecuadamente.
El jupyter notebook contiene los siguientes secciones:
Utiliza este notebook para futuras referencias y cómo una guía para graficar con python.
Estas son las primeras 30 filas del dataset en el que estaremos trabajando.
Observa que hemos importado las librerías de pandas, matplotlib y plotly.
import pandas as pd
import matplotlib.pyplot as plt
import plotly.express as px
#Render en el notebook
import plotly.io as pio
pio.renderers.default = "notebook"
#Especificando la ruta
wd = "../datasets/raw/"
#Cargando el dataset
df = pd.read_csv(wd+"cars.csv")
df.head(30)
| mpg | cylinders | displacement | horsepower | weight | acceleration | model year | origin | car name | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 18.0 | 8 | 307.0 | 130.0 | 3504 | 12.0 | 70 | 1 | chevrolet chevelle malibu |
| 1 | 15.0 | 8 | 350.0 | 165.0 | 3693 | 11.5 | 70 | 1 | buick skylark 320 |
| 2 | 18.0 | 8 | 318.0 | 150.0 | 3436 | 11.0 | 70 | 1 | plymouth satellite |
| 3 | 16.0 | 8 | 304.0 | 150.0 | 3433 | 12.0 | 70 | 1 | amc rebel sst |
| 4 | 17.0 | 8 | 302.0 | 140.0 | 3449 | 10.5 | 70 | 1 | ford torino |
| 5 | 15.0 | 8 | 429.0 | 198.0 | 4341 | 10.0 | 70 | 1 | ford galaxie 500 |
| 6 | 14.0 | 8 | 454.0 | 220.0 | 4354 | 9.0 | 70 | 1 | chevrolet impala |
| 7 | 14.0 | 8 | 440.0 | 215.0 | 4312 | 8.5 | 70 | 1 | plymouth fury iii |
| 8 | 14.0 | 8 | 455.0 | 225.0 | 4425 | 10.0 | 70 | 1 | pontiac catalina |
| 9 | 15.0 | 8 | 390.0 | 190.0 | 3850 | 8.5 | 70 | 1 | amc ambassador dpl |
| 10 | 15.0 | 8 | 383.0 | 170.0 | 3563 | 10.0 | 70 | 1 | dodge challenger se |
| 11 | 14.0 | 8 | 340.0 | 160.0 | 3609 | 8.0 | 70 | 1 | plymouth 'cuda 340 |
| 12 | 15.0 | 8 | 400.0 | 150.0 | 3761 | 9.5 | 70 | 1 | chevrolet monte carlo |
| 13 | 14.0 | 8 | 455.0 | 225.0 | 3086 | 10.0 | 70 | 1 | buick estate wagon (sw) |
| 14 | 24.0 | 4 | 113.0 | 95.0 | 2372 | 15.0 | 70 | 3 | toyota corona mark ii |
| 15 | 22.0 | 6 | 198.0 | 95.0 | 2833 | 15.5 | 70 | 1 | plymouth duster |
| 16 | 18.0 | 6 | 199.0 | 97.0 | 2774 | 15.5 | 70 | 1 | amc hornet |
| 17 | 21.0 | 6 | 200.0 | 85.0 | 2587 | 16.0 | 70 | 1 | ford maverick |
| 18 | 27.0 | 4 | 97.0 | 88.0 | 2130 | 14.5 | 70 | 3 | datsun pl510 |
| 19 | 26.0 | 4 | 97.0 | 46.0 | 1835 | 20.5 | 70 | 2 | volkswagen 1131 deluxe sedan |
| 20 | 25.0 | 4 | 110.0 | 87.0 | 2672 | 17.5 | 70 | 2 | peugeot 504 |
| 21 | 24.0 | 4 | 107.0 | 90.0 | 2430 | 14.5 | 70 | 2 | audi 100 ls |
| 22 | 25.0 | 4 | 104.0 | 95.0 | 2375 | 17.5 | 70 | 2 | saab 99e |
| 23 | 26.0 | 4 | 121.0 | 113.0 | 2234 | 12.5 | 70 | 2 | bmw 2002 |
| 24 | 21.0 | 6 | 199.0 | 90.0 | 2648 | 15.0 | 70 | 1 | amc gremlin |
| 25 | 10.0 | 8 | 360.0 | 215.0 | 4615 | 14.0 | 70 | 1 | ford f250 |
| 26 | 10.0 | 8 | 307.0 | 200.0 | 4376 | 15.0 | 70 | 1 | chevy c20 |
| 27 | 11.0 | 8 | 318.0 | 210.0 | 4382 | 13.5 | 70 | 1 | dodge d200 |
| 28 | 9.0 | 8 | 304.0 | 193.0 | 4732 | 18.5 | 70 | 1 | hi 1200d |
| 29 | 27.0 | 4 | 97.0 | 88.0 | 2130 | 14.5 | 71 | 3 | datsun pl510 |
Marca: Puntos (principalmente círculos pero puede involucrar cualquier primitiva geométrica)
Tipo de variable: Numérica.
Contexto: Dispersión, tendencia, agrupamiento.
Recuerda, nuestras variables tienen que ser numéricas y por lo regular continuas.
Para este ejemplo, tomaremos las columnas weight y mpg del dataset principal y trataremos de ver si existe algún patrón o relación.
#matplotlib
plt.scatter(df["weight"], df["mpg"])
<matplotlib.collections.PathCollection at 0x166aceeb790>
#plotly
px.scatter(x="weight", y="mpg",data_frame=df)
Marca: Línea
Tipo de variable: El eje x suele ser una variable temporal y otras veces una variable categórica secuencial. Habrá ocasiones en que ambos ejes tendrán variables numéricas (v.g.: correlación entre dos variables)
Contexto: Tendencia.
Para este ejemplo, tomaremos las columnas weight y mpg del dataset principal. Cómo queremos resaltar una tendencia, y evitar las oscilaciones del dataset, vamos a ordenar nuestros datos en función de weight, y después haremos un rolling average.
# Preparación de los datos
#Creando un segundo dataset ordenado por weight
df_w = df.sort_values(by="weight").reset_index(drop=True)
#Asignando a otra columna en el dataset con el rolling avg
df_w["mpg_avg"] = (df_w.sort_values(by="weight")["mpg"] #sort by mpg
.rolling(window=15,center=True) #calculate rolling operation
.mean()) #calculate the average
df_w.head(10)
| mpg | cylinders | displacement | horsepower | weight | acceleration | model year | origin | car name | mpg_avg | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 35.0 | 4 | 72.0 | 69.0 | 1613 | 18.0 | 71 | 3 | datsun 1200 | NaN |
| 1 | 31.0 | 4 | 76.0 | 52.0 | 1649 | 16.5 | 74 | 3 | toyota corona | NaN |
| 2 | 39.1 | 4 | 79.0 | 58.0 | 1755 | 16.9 | 81 | 3 | toyota starlet | NaN |
| 3 | 35.1 | 4 | 81.0 | 60.0 | 1760 | 16.1 | 81 | 3 | honda civic 1300 | NaN |
| 4 | 31.0 | 4 | 71.0 | 65.0 | 1773 | 19.0 | 71 | 3 | toyota corolla 1200 | NaN |
| 5 | 33.0 | 4 | 91.0 | 53.0 | 1795 | 17.4 | 76 | 3 | honda civic | NaN |
| 6 | 33.0 | 4 | 91.0 | 53.0 | 1795 | 17.5 | 75 | 3 | honda civic cvcc | NaN |
| 7 | 36.1 | 4 | 98.0 | 66.0 | 1800 | 14.4 | 78 | 1 | ford fiesta | 33.386667 |
| 8 | 36.1 | 4 | 91.0 | 60.0 | 1800 | 16.4 | 78 | 3 | honda civic cvcc | 33.040000 |
| 9 | 36.0 | 4 | 79.0 | 58.0 | 1825 | 18.6 | 77 | 2 | renault 5 gtl | 33.946667 |
Graficando con los datos preparados:
#matplotlib
plt.plot(df_w["weight"], df_w["mpg_avg"])
[<matplotlib.lines.Line2D at 0x166b0979fa0>]
#plotly
px.line(x="weight", y="mpg_avg",data_frame=df_w)
Canal 2: Color.
Marca: Línea
Tipo de variable: El eje x suele ser una variable temporal y otras veces una variable categórica secuencial. Habrá ocasiones en que ambos ejes tendrán variables numéricas (v.g.: correlación entre dos variables de diferentes categorías)
Contexto: Tendencia, comparar
En este ejemplo vamos a crear un dataset agregado dónde la columna base será year, y obtendremos el promedio de la acelaración por intervalos de horsepower. La idea es ver si podemos ver el incremento/decremento de la aceleración por año por cada intervalo de horsepower.
El primer paso es obtener los bins o, dicho de otra forma, crear las categorías de horsepower.
Observa cómo el nuevo dataset contiene la columna HP_bins que vamos a crear en la siguiente celda
#Creando un dataset aparte
df3 = df.copy()
#Necesitamos especificar algunas etiquetas que serán las categorías
labels = ["HP40-70","HP70-100","HP100-130"]
#Y los bins, que son los cortes:
bins = [39,69.9999,99.9999,131]
#Y ejecutar pd.cut
df3["HP_bins"] = pd.cut(df3["horsepower"],bins, labels=labels)
#Y tirar los valores nulos
df3 = df3.dropna()
df3.head(10)
| mpg | cylinders | displacement | horsepower | weight | acceleration | model year | origin | car name | HP_bins | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 18.0 | 8 | 307.0 | 130.0 | 3504 | 12.0 | 70 | 1 | chevrolet chevelle malibu | HP100-130 |
| 14 | 24.0 | 4 | 113.0 | 95.0 | 2372 | 15.0 | 70 | 3 | toyota corona mark ii | HP70-100 |
| 15 | 22.0 | 6 | 198.0 | 95.0 | 2833 | 15.5 | 70 | 1 | plymouth duster | HP70-100 |
| 16 | 18.0 | 6 | 199.0 | 97.0 | 2774 | 15.5 | 70 | 1 | amc hornet | HP70-100 |
| 17 | 21.0 | 6 | 200.0 | 85.0 | 2587 | 16.0 | 70 | 1 | ford maverick | HP70-100 |
| 18 | 27.0 | 4 | 97.0 | 88.0 | 2130 | 14.5 | 70 | 3 | datsun pl510 | HP70-100 |
| 19 | 26.0 | 4 | 97.0 | 46.0 | 1835 | 20.5 | 70 | 2 | volkswagen 1131 deluxe sedan | HP40-70 |
| 20 | 25.0 | 4 | 110.0 | 87.0 | 2672 | 17.5 | 70 | 2 | peugeot 504 | HP70-100 |
| 21 | 24.0 | 4 | 107.0 | 90.0 | 2430 | 14.5 | 70 | 2 | audi 100 ls | HP70-100 |
| 22 | 25.0 | 4 | 104.0 | 95.0 | 2375 | 17.5 | 70 | 2 | saab 99e | HP70-100 |
El siguiente paso es agrupar el dataset
#Agregado (agrupar)
df3 = df3.groupby(["model year","HP_bins"],as_index=False)["acceleration"].mean()
df3
| model year | HP_bins | acceleration | |
|---|---|---|---|
| 0 | 70 | HP40-70 | 20.500000 |
| 1 | 70 | HP70-100 | 15.666667 |
| 2 | 70 | HP100-130 | 12.250000 |
| 3 | 71 | HP40-70 | 18.666667 |
| 4 | 71 | HP70-100 | 15.954545 |
| 5 | 71 | HP100-130 | 14.666667 |
| 6 | 72 | HP40-70 | 20.750000 |
| 7 | 72 | HP70-100 | 16.541667 |
| 8 | 72 | HP100-130 | 14.250000 |
| 9 | 73 | HP40-70 | 20.250000 |
| 10 | 73 | HP70-100 | 16.450000 |
| 11 | 73 | HP100-130 | 15.312500 |
| 12 | 74 | HP40-70 | 17.833333 |
| 13 | 74 | HP70-100 | 15.550000 |
| 14 | 74 | HP100-130 | 16.900000 |
| 15 | 75 | HP40-70 | 17.500000 |
| 16 | 75 | HP70-100 | 16.625000 |
| 17 | 75 | HP100-130 | 16.055556 |
| 18 | 76 | HP40-70 | 20.566667 |
| 19 | 76 | HP70-100 | 16.640000 |
| 20 | 76 | HP100-130 | 15.622222 |
| 21 | 77 | HP40-70 | 17.625000 |
| 22 | 77 | HP70-100 | 15.918182 |
| 23 | 77 | HP100-130 | 15.885714 |
| 24 | 78 | HP40-70 | 17.466667 |
| 25 | 78 | HP70-100 | 15.961538 |
| 26 | 78 | HP100-130 | 16.340000 |
| 27 | 79 | HP40-70 | 16.366667 |
| 28 | 79 | HP70-100 | 17.038462 |
| 29 | 79 | HP100-130 | 14.675000 |
| 30 | 80 | HP40-70 | 18.772727 |
| 31 | 80 | HP70-100 | 16.515385 |
| 32 | 80 | HP100-130 | 13.450000 |
| 33 | 81 | HP40-70 | 17.170000 |
| 34 | 81 | HP70-100 | 16.400000 |
| 35 | 81 | HP100-130 | 14.766667 |
| 36 | 82 | HP40-70 | 17.428571 |
| 37 | 82 | HP70-100 | 16.295238 |
| 38 | 82 | HP100-130 | 15.550000 |
#matplotlib
#Observa cómo necesitamos iterar por cada valor único de HP_bins
hp_cats = df3["HP_bins"].unique().tolist()
for hp in hp_cats:
tmp_subset = df3[df3["HP_bins"]==hp]
plt.plot(tmp_subset["model year"], tmp_subset["acceleration"])
#plotly
px.line(x="model year", y="acceleration", color="HP_bins", data_frame=df3)
Marca: Polígono irregular
Tipo de variable: El eje x suele ser una variable temporal y otras veces una variable categórica secuencial. La altura del área viene dado por el valor numérico del eje y. Habrá algunas ocasiones en que ambas variables son numéricas (v.g.: distribuciones de probabilidad).
Contexto: Tendencia. También puede servir para mostrar una distribución
Para este ejemplo vamos a volver a visualizar el año del modelo y agregar las millas por galón (mpg) a través del promedio.
#Agregar (agrupar por año del modelo y mpg promedio)
df4 = df.groupby("model year",as_index=False)["mpg"].mean()
df4
| model year | mpg | |
|---|---|---|
| 0 | 70 | 17.689655 |
| 1 | 71 | 21.250000 |
| 2 | 72 | 18.714286 |
| 3 | 73 | 17.100000 |
| 4 | 74 | 22.703704 |
| 5 | 75 | 20.266667 |
| 6 | 76 | 21.573529 |
| 7 | 77 | 23.375000 |
| 8 | 78 | 24.061111 |
| 9 | 79 | 25.093103 |
| 10 | 80 | 33.696552 |
| 11 | 81 | 30.334483 |
| 12 | 82 | 31.709677 |
#matplotlib
plt.fill_between(df4["model year"], df4["mpg"])
<matplotlib.collections.PolyCollection at 0x166b101dbb0>
#plotly
px.area(x="model year", y="mpg",data_frame=df4)
Canal 2: Color (En ocasiones posición).
Marca: Polígono irregular
Tipo de variable: El eje x suele ser una variable temporal y otras veces una variable categórica secuencial. La altura del área viene dado por el valor numérico del eje y. Habrá algunas ocasiones en que ambas variables son numéricas (v.g.: distribuciones de probabilidad).
Contexto: Tendencia o comparar comportamiento de variables categóricas. También puede servir para mostrar una distribución.
Para este ejemplo vamos a tratar de observar la evolución de los caballos (horsepower) de fuerza a través del tiempo pero buscando diferencias en intervalos de la variable weight, por lo que una categoría irá de 1000 libras a 2000 libras, 2000 libras a 4000 libras y más de 4000 libras.
Observa que para lograr visualizar las diferentes categorías cambiamos el orden de aparaición el gráfico, el área más grande al fondo y las más pequeñas al frente.
#Creando un dataset aparte
df5 = df.copy()
#Necesitamos especificar algunas etiquetas que serán las categorías
labels = ["HP(W1K-2K)","HP(W2K-4K)","HP(4K+)"]
#Y los bins, que son los cortes (Observa el último dígito, es exageradamete grande
# porque queremos considerar "infinito" cómo cota superior"):
bins = [999,1999.9999,3999.9999,999999]
#Y ejecutar pd.cut
df5["HP_W_bins"] = pd.cut(df5["weight"],bins, labels=labels)
#Y tirar los valores nulos
df5 = df5.dropna()
df5.head(10)
| mpg | cylinders | displacement | horsepower | weight | acceleration | model year | origin | car name | HP_W_bins | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 18.0 | 8 | 307.0 | 130.0 | 3504 | 12.0 | 70 | 1 | chevrolet chevelle malibu | HP(W2K-4K) |
| 1 | 15.0 | 8 | 350.0 | 165.0 | 3693 | 11.5 | 70 | 1 | buick skylark 320 | HP(W2K-4K) |
| 2 | 18.0 | 8 | 318.0 | 150.0 | 3436 | 11.0 | 70 | 1 | plymouth satellite | HP(W2K-4K) |
| 3 | 16.0 | 8 | 304.0 | 150.0 | 3433 | 12.0 | 70 | 1 | amc rebel sst | HP(W2K-4K) |
| 4 | 17.0 | 8 | 302.0 | 140.0 | 3449 | 10.5 | 70 | 1 | ford torino | HP(W2K-4K) |
| 5 | 15.0 | 8 | 429.0 | 198.0 | 4341 | 10.0 | 70 | 1 | ford galaxie 500 | HP(4K+) |
| 6 | 14.0 | 8 | 454.0 | 220.0 | 4354 | 9.0 | 70 | 1 | chevrolet impala | HP(4K+) |
| 7 | 14.0 | 8 | 440.0 | 215.0 | 4312 | 8.5 | 70 | 1 | plymouth fury iii | HP(4K+) |
| 8 | 14.0 | 8 | 455.0 | 225.0 | 4425 | 10.0 | 70 | 1 | pontiac catalina | HP(4K+) |
| 9 | 15.0 | 8 | 390.0 | 190.0 | 3850 | 8.5 | 70 | 1 | amc ambassador dpl | HP(W2K-4K) |
El siguiente paso es pivotear el dataset
#Agregado (agrupar)
df5 = df5.groupby(["model year","HP_W_bins"],as_index=False)["horsepower"].mean()
df5
| model year | HP_W_bins | horsepower | |
|---|---|---|---|
| 0 | 70 | HP(W1K-2K) | 46.000000 |
| 1 | 70 | HP(W2K-4K) | 128.250000 |
| 2 | 70 | HP(4K+) | 209.500000 |
| 3 | 71 | HP(W1K-2K) | 66.000000 |
| 4 | 71 | HP(W2K-4K) | 91.125000 |
| 5 | 71 | HP(4K+) | 166.857143 |
| 6 | 72 | HP(W1K-2K) | NaN |
| 7 | 72 | HP(W2K-4K) | 93.470588 |
| 8 | 72 | HP(4K+) | 161.454545 |
| 9 | 73 | HP(W1K-2K) | 47.500000 |
| 10 | 73 | HP(W2K-4K) | 111.416667 |
| 11 | 73 | HP(4K+) | 175.000000 |
| 12 | 74 | HP(W1K-2K) | 62.750000 |
| 13 | 74 | HP(W2K-4K) | 86.411765 |
| 14 | 74 | HP(4K+) | 146.000000 |
| 15 | 75 | HP(W1K-2K) | 61.500000 |
| 16 | 75 | HP(W2K-4K) | 95.666667 |
| 17 | 75 | HP(4K+) | 153.250000 |
| 18 | 76 | HP(W1K-2K) | 66.000000 |
| 19 | 76 | HP(W2K-4K) | 96.280000 |
| 20 | 76 | HP(4K+) | 153.400000 |
| 21 | 77 | HP(W1K-2K) | 68.250000 |
| 22 | 77 | HP(W2K-4K) | 93.823529 |
| 23 | 77 | HP(4K+) | 153.428571 |
| 24 | 78 | HP(W1K-2K) | 59.400000 |
| 25 | 78 | HP(W2K-4K) | 105.066667 |
| 26 | 78 | HP(4K+) | 140.000000 |
| 27 | 79 | HP(W1K-2K) | 72.000000 |
| 28 | 79 | HP(W2K-4K) | 100.916667 |
| 29 | 79 | HP(4K+) | 148.500000 |
| 30 | 80 | HP(W1K-2K) | 63.000000 |
| 31 | 80 | HP(W2K-4K) | 79.291667 |
| 32 | 80 | HP(4K+) | NaN |
| 33 | 81 | HP(W1K-2K) | 63.000000 |
| 34 | 81 | HP(W2K-4K) | 84.956522 |
| 35 | 81 | HP(4K+) | NaN |
| 36 | 82 | HP(W1K-2K) | 68.600000 |
| 37 | 82 | HP(W2K-4K) | 84.040000 |
| 38 | 82 | HP(4K+) | NaN |
#matplotlib
#Observa cómo necesitamos iterar por cada valor único de HP_bins
hp_cats = ["HP(4K+)","HP(W2K-4K)","HP(W1K-2K)"]
for hp in hp_cats:
tmp_subset = df5[df5["HP_W_bins"]==hp]
plt.fill_between(tmp_subset["model year"], tmp_subset["horsepower"])
#plotly
# Para plotly express necesitamos hacer algo extra, de otra manera intentará crear stacked area charts
import plotly.graph_objects as go
hp_cats = ["HP(4K+)","HP(W2K-4K)","HP(W1K-2K)"]
fig = go.Figure()
for hp in hp_cats:
tmp_subset = df5[df5["HP_W_bins"]==hp]
fig.add_trace(go.Scatter(x=tmp_subset["model year"], y=tmp_subset["horsepower"], fill='tozeroy'))
fig.show()
Marca: Barra (rectángulo.)
Tipo de variable: Variable categórica, y la altura se mapea a través de una variable numérica.
Contexto: Comparar.
#Agregando dataset
df6 = df.groupby("cylinders",as_index=False)["acceleration"].mean()
df6
| cylinders | acceleration | |
|---|---|---|
| 0 | 3 | 13.250000 |
| 1 | 4 | 16.601471 |
| 2 | 5 | 18.633333 |
| 3 | 6 | 16.263095 |
| 4 | 8 | 12.955340 |
#matplotlib
plt.bar(df6["cylinders"],df6["acceleration"])
plt.show()
#plotlty
px.bar(x="cylinders",y="acceleration",data_frame=df6)
Marca: Barra (rectángulo.)
Tipo de variable: Variable categórica, y la longitudse mapea a través de una variable numérica.
Contexto: Comparar.
#Preparando el dataset
#Subset por columna
df7 = df[["car name"]]
#Quitando la marca
df7 = df7["car name"].str.split(" ")
#Creando una lista
df7 = df7.tolist()
#Creando una lista plana
df7 = [carname for sublist in df7 for carname in sublist]
#Contando repeticiones y regresando el top 10 (desde abajo)
df7=pd.DataFrame(df7)[0].value_counts(ascending=True).tail(10)
df7 = pd.DataFrame(df7).reset_index().rename(columns={0:"count",'index':"marca"})
df7
| marca | count | |
|---|---|---|
| 0 | buick | 17 |
| 1 | custom | 18 |
| 2 | datsun | 23 |
| 3 | toyota | 25 |
| 4 | amc | 28 |
| 5 | (sw) | 28 |
| 6 | dodge | 28 |
| 7 | plymouth | 31 |
| 8 | chevrolet | 43 |
| 9 | ford | 51 |
#matplotlib
plt.barh(df7["marca"],df7["count"])
plt.show()
#plotly
#plotlty
px.bar(y="marca",x="count",data_frame=df7)
Marca: Arco de círculo
Tipo de variable: Variable categórica.
Contexto: Comparar partes del todo.
#Agrupar por displacement
df8 = df.copy()
#Necesitamos especificar algunas etiquetas que serán las categorías
labels = ["0-100","100-200","200-300","300+"]
#Y los bins, que son los cortes:
bins = [0,100,200,300,999999]
#Y ejecutar pd.cut
df8["displacement_bins"] = pd.cut(df8["displacement"],bins, labels=labels)
#Y tirar los valores nulos
#df8 = df8.dropna()
df8.head(10)
| mpg | cylinders | displacement | horsepower | weight | acceleration | model year | origin | car name | displacement_bins | |
|---|---|---|---|---|---|---|---|---|---|---|
| 0 | 18.0 | 8 | 307.0 | 130.0 | 3504 | 12.0 | 70 | 1 | chevrolet chevelle malibu | 300+ |
| 1 | 15.0 | 8 | 350.0 | 165.0 | 3693 | 11.5 | 70 | 1 | buick skylark 320 | 300+ |
| 2 | 18.0 | 8 | 318.0 | 150.0 | 3436 | 11.0 | 70 | 1 | plymouth satellite | 300+ |
| 3 | 16.0 | 8 | 304.0 | 150.0 | 3433 | 12.0 | 70 | 1 | amc rebel sst | 300+ |
| 4 | 17.0 | 8 | 302.0 | 140.0 | 3449 | 10.5 | 70 | 1 | ford torino | 300+ |
| 5 | 15.0 | 8 | 429.0 | 198.0 | 4341 | 10.0 | 70 | 1 | ford galaxie 500 | 300+ |
| 6 | 14.0 | 8 | 454.0 | 220.0 | 4354 | 9.0 | 70 | 1 | chevrolet impala | 300+ |
| 7 | 14.0 | 8 | 440.0 | 215.0 | 4312 | 8.5 | 70 | 1 | plymouth fury iii | 300+ |
| 8 | 14.0 | 8 | 455.0 | 225.0 | 4425 | 10.0 | 70 | 1 | pontiac catalina | 300+ |
| 9 | 15.0 | 8 | 390.0 | 190.0 | 3850 | 8.5 | 70 | 1 | amc ambassador dpl | 300+ |
Después de agregar el dataset, podemos proceder a agrupar los bins que acabamos de calcular. En este caso bastará con hacer un value_counts con pandas
#group by
df8 = (pd.DataFrame(df8["displacement_bins"]
.value_counts(normalize=True,sort=False))
.reset_index()
.rename(columns={"index":"displacement","displacement_bins":"percent"}))
df8
| displacement | percent | |
|---|---|---|
| 0 | 0-100 | 0.246231 |
| 1 | 100-200 | 0.356784 |
| 2 | 200-300 | 0.150754 |
| 3 | 300+ | 0.246231 |
#matplotib
plt.pie(df8["percent"])
plt.show()
#plotly
px.pie(values="percent",names="displacement",data_frame=df8)